<template>
  <div class="page-container">
    <div class="page-header">
      <h1 class="page-title">{{ isEdit ? '编辑数据源' : '新增数据源' }}</h1>
      <p class="page-subtitle">配置数据源连接信息</p>
    </div>

    <div class="form-container">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        label-position="left"
      >
        <el-form-item label="数据源名称" prop="name">
          <el-input
            v-model="form.name"
            placeholder="请输入数据源名称"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="数据源类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择数据源类型" style="width: 100%">
            <el-option label="MySQL" value="mysql" />
            <el-option label="MongoDB" value="mongodb" />
            <el-option label="PostgreSQL" value="postgresql" />
            <el-option label="Oracle" value="oracle" />
          </el-select>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="16">
            <el-form-item label="主机地址" prop="host">
              <el-input v-model="form.host" placeholder="请输入主机地址" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="端口" prop="port">
              <el-input-number
                v-model="form.port"
                :min="1"
                :max="65535"
                placeholder="端口号"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="数据库名" prop="database">
          <el-input v-model="form.database" placeholder="请输入数据库名称" />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="form.username" placeholder="请输入用户名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input
                v-model="form.password"
                type="password"
                placeholder="请输入密码"
                show-password
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="描述">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入数据源描述（可选）"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <div class="form-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="info" @click="handleTest" :loading="testing">测试连接</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  getDatasourceDetail, 
  createDatasource, 
  updateDatasource, 
  testDatasourceConnection 
} from '@/api/datasource'

const router = useRouter()
const route = useRoute()
const formRef = ref()
const testing = ref(false)
const submitting = ref(false)

// 判断是否为编辑模式
const isEdit = computed(() => !!route.params.id)

// 表单数据
const form = reactive({
  name: '',
  type: 'mysql',
  host: '',
  port: 3306,
  database: '',
  username: '',
  password: '',
  description: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入数据源名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择数据源类型', trigger: 'change' }
  ],
  host: [
    { required: true, message: '请输入主机地址', trigger: 'blur' }
  ],
  port: [
    { required: true, message: '请输入端口号', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        const port = Number(value)
        if (!port || port < 1 || port > 65535) {
          callback(new Error('端口号范围 1-65535'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ],
  database: [
    { required: true, message: '请输入数据库名称', trigger: 'blur' }
  ],
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

// 监听类型变化，设置默认端口
const handleTypeChange = () => {
  const portMap = {
    mysql: 3306,
    mongodb: 27017,
    postgresql: 5432,
    oracle: 1521
  }
  form.port = portMap[form.type] || 3306
}

// 测试连接
const handleTest = async () => {
  try {
    await formRef.value.validateField(['host', 'port', 'username', 'password', 'database'])
    
    testing.value = true
    await testDatasourceConnection({
      type: form.type,
      host: form.host,
      port: form.port,
      username: form.username,
      password: form.password,
      database: form.database
    })
    ElMessage.success('连接测试成功！')
  } catch (error) {
    if (error === false) {
      ElMessage.error('请先填写完整的连接信息')
    } else if (error.response?.data?.message) {
      ElMessage.error(`连接测试失败: ${error.response.data.message}`)
    } else {
      ElMessage.error('连接测试失败，请检查连接信息')
    }
  } finally {
    testing.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    submitting.value = true
    
    const datasourceData = {
      name: form.name,
      type: form.type,
      host: form.host,
      port: Number(form.port),
      username: form.username,
      password: form.password,
      database: form.database,
      description: form.description
    }
    
    if (isEdit.value) {
      await updateDatasource(route.params.id, datasourceData)
      ElMessage.success('更新成功！')
    } else {
      await createDatasource(datasourceData)
      ElMessage.success('创建成功！')
    }
    
    router.push('/datasource')
  } catch (error) {
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else if (error.message) {
      ElMessage.error(error.message)
    } else {
      ElMessage.error('操作失败，请检查输入信息')
    }
  } finally {
    submitting.value = false
  }
}

// 取消操作
const handleCancel = () => {
  router.back()
}

// 加载数据（编辑模式）
const loadData = async () => {
  if (isEdit.value) {
    try {
      const res = await getDatasourceDetail(route.params.id)
      const datasourceData = res.data
      
      Object.assign(form, {
        name: datasourceData.name,
        type: datasourceData.type,
        host: datasourceData.host,
        port: datasourceData.port,
        username: datasourceData.username,
        password: '', // 出于安全考虑，不显示密码
        database: datasourceData.database,
        description: datasourceData.description || ''
      })
    } catch (error) {
      ElMessage.error('获取数据源信息失败')
      router.back()
    }
  }
}

onMounted(() => {
  loadData()
})
</script>

<style lang="scss" scoped>
:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input-number) {
  width: 100%;
}
</style>